﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using Microsoft.Win32;
using BesAsm.Stormwater.Swmm5Results;
using BesAsm.Stormwater.TimeSeries;

namespace BesAsm.Stormwater.Swmm5ResultsUi.Presentation.Views
{
  /// <summary>
  /// Interaction logic for TimeSeriesTools.xaml
  /// </summary>
  public partial class TimeSeriesTool : Page
  {
    private TextReader _reader;
    private TimeSeries<float> _ts;

    public TimeSeriesTool()
    {
      InitializeComponent();
    }

    private void btnBrowseCsv_Click(object sender, RoutedEventArgs e)
    {
      OpenFileDialog ofd = new OpenFileDialog();
      ofd.AddExtension = true;
      ofd.Filter = "CSV File|*.csv|All Files|*.*";
      ofd.Title = "Select a .csv time-series file to modify";

      if (ofd.ShowDialog() != true)
        return;

      string file = ofd.FileName;
      txtCsvFile.Text = file;

      try
      {
        OpenTimeSeries(file);
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message, "Error parsing file!", MessageBoxButton.OK, MessageBoxImage.Error);
      }
    }

    private void btnExport_Click(object sender, RoutedEventArgs e)
    {
      SaveFileDialog sfd = new SaveFileDialog();

      sfd.AddExtension = true;
      sfd.Filter = "CSV File|*.csv|All Files|*.*";
      sfd.Title = "Choose a location to save the modified time-series file";

      if (sfd.ShowDialog() != true)
        return;

      string file = sfd.FileName;

      try
      {
        SaveTimeSeries(file);
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message, "Error exporting file!", MessageBoxButton.OK, MessageBoxImage.Error);
      }
    }

    private void OpenTimeSeries(string file)
    {
      _reader = new StreamReader(file);
      try
      {
        ValidateTimeSeries(file);
      }
      finally
      {
        _reader.Close();
      }

    }

    private void ValidateTimeSeries(string file)
    {
      char[] splitChars = new char[] { ',' };

      int columnCount = 0;
      string[] columnNames;

      _ts = new TimeSeries<float>();

      string line = _reader.ReadLine();
      string[] tokens = line.Split(splitChars);

      DateTime dt;

      bool hasHeader = false;
      if (!DateTime.TryParse(tokens[0], out dt))
      {
        hasHeader = true;
        line = _reader.ReadLine();
        tokens = line.Split(splitChars);
        if (!DateTime.TryParse(tokens[0], out dt))
          throw new ArgumentException("Could not parse file " + file);
      }

      columnCount = tokens.Length - 1;
      columnNames = new string[columnCount];

      for (int i = 0; i < columnCount; i++)
      {
        if (hasHeader)
          columnNames[i] = tokens[i + 1];
        else
          columnNames[i] = "Column" + i;
      }
      _ts.Name = columnNames[0];

      float f = 0;

      while (line != null)
      {                
        tokens = line.Split(splitChars);

        if (!DateTime.TryParse(tokens[0], out dt))
          throw new ArgumentException("Could not parse file " + file);
        if (!float.TryParse(tokens[1], out f))
          throw new ArgumentException("Could not parse file " + file);

        try
        {
          if (!_ts.ContainsKey(dt))
          _ts.Add(dt, f);
        }
        catch (Exception ex)
        {
        }
        line = _reader.ReadLine();
      }
    }

    private void SaveTimeSeries(string file)
    {
      ResampleType type;

      if (comboBox2.Text == "Average")
        type = ResampleType.Average;
      else if (comboBox2.Text == "Total")
        type = ResampleType.Total;
      else
        throw new NotImplementedException();

      TimeSeries<float> newTs = _ts.Resample(
        new TimeSpan(1, 0, 0, 0), 
        new DateTime(_ts.StartDate.Year, _ts.StartDate.Month, _ts.StartDate.Day),
        new DateTime(_ts.EndDate.Year, _ts.EndDate.Month, _ts.EndDate.Day), 
        type);
      newTs.WriteTimeSeries(file);
    }
  }
}
